// 登录功能修复测试
console.log('开始测试登录功能修复...');

// 模拟环境
const localStorage = global.localStorage || {
  _data: {},
  getItem(key) {
    return this._data[key];
  },
  setItem(key, value) {
    this._data[key] = value;
  },
  removeItem(key) {
    delete this._data[key];
  },
  clear() {
    this._data = {};
  }
};

// 模拟Element Plus消息组件
const ElMessage = {
  success: (msg) => console.log(`[成功] ${msg}`),
  error: (msg) => console.log(`[错误] ${msg}`),
  warning: (msg) => console.log(`[警告] ${msg}`)
};

// 模拟router
const router = {
  push: (path) => console.log(`[路由] 导航到 ${path}`)
};

// 测试登录函数
async function testLogin(username, password) {
  console.log(`[测试] 尝试登录 - 用户名: ${username}, 密码: ${password.replace(/./g, '*')}`);
  
  try {
    // 模拟登录请求
    const response = await fetch('https://zmyzmy.xin/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        username,
        password
      })
    });
    
    const result = await response.json();
    console.log('[响应] 状态码:', response.status);
    console.log('[响应] 数据:', result);
    
    if (response.ok && result.code === 200 && result.data && result.data.token) {
      // 测试token存储方式
      const token = result.data.token;
      localStorage.setItem('token', `Bearer ${token}`);
      
      // 验证token
      try {
        const tokenParts = token.split('.');
        if (tokenParts.length === 3) {
          const payload = JSON.parse(atob(tokenParts[1]));
          console.log('[Token] 有效载荷:', payload);
          console.log('[Token] 过期时间:', new Date(payload.exp * 1000).toLocaleString());
        }
      } catch (e) {
        console.error('[Token] 解析失败:', e);
      }
      
      // 存储用户信息
      if (result.data.userInfo) {
        localStorage.setItem('userInfo', JSON.stringify(result.data.userInfo));
      }
      
      // 验证token格式
      const storedToken = localStorage.getItem('token');
      console.log('[存储] Token:', storedToken);
      console.log('[验证] Token格式正确:', storedToken.startsWith('Bearer '));
      
      return true;
    } else {
      console.error('[登录] 失败:', result.message || '未知错误');
      return false;
    }
  } catch (error) {
    console.error('[请求] 异常:', error.message);
    return false;
  }
}

// 测试API状态检查
async function testApiStatus() {
  console.log('[测试] 检查API状态');
  
  try {
    const token = localStorage.getItem('token') || '';
    
    const response = await fetch('https://zmyzmy.xin/api/auth/test', {
      headers: {
        'Authorization': token
      }
    });
    
    console.log('[API状态] 响应码:', response.status);
    
    if (response.ok) {
      try {
        const data = await response.json();
        console.log('[API状态] 成功:', data);
        return true;
      } catch (e) {
        console.log('[API状态] 响应不是JSON格式');
        return response.status === 200;
      }
    } else {
      console.error('[API状态] 检查失败');
      return false;
    }
  } catch (error) {
    console.error('[API状态] 请求异常:', error.message);
    return false;
  }
}

// 运行测试
(async () => {
  console.log('========== 开始测试 ==========');
  
  // 清除之前的状态
  localStorage.clear();
  
  // 测试正确的登录凭据
  console.log('\n[测试用例 1] 使用正确凭据登录');
  const loginResult = await testLogin('admin', '123456');
  
  if (loginResult) {
    console.log('[结果] 登录成功！');
    
    // 测试API状态
    console.log('\n[测试用例 2] 检查API状态');
    const apiStatusResult = await testApiStatus();
    
    if (apiStatusResult) {
      console.log('[结果] API状态检查成功！');
    } else {
      console.log('[结果] API状态检查失败');
    }
  } else {
    console.log('[结果] 登录失败');
  }
  
  console.log('\n========== 测试完成 ==========');
})();
